package com.saas.platform.demo.base.advice;

import java.lang.reflect.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import com.alibaba.fastjson.JSON;
import com.saas.ability.core.base.protocol.BaseInput;
import com.saas.ability.core.base.util.MethodParameterUtils;

@ControllerAdvice
public class JsonRequestBodyAdvice extends RequestBodyAdviceAdapter {
	
	Logger logger = LoggerFactory.getLogger(JsonRequestBodyAdvice.class);


	@Override
	public boolean supports(MethodParameter methodParameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		return BaseInput.class.isAssignableFrom(methodParameter.getParameterType());
	}


	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		BaseInput baseInput = (BaseInput)body;
		logger.debug("接口请求参数,baseInput:{}", baseInput);
		
		Object obj = baseInput.getParams();
		if(obj == null){
			logger.warn("接口的params为空,methodName:{}", parameter.getMethod().getName());
		}else{
			Class<?> clazz = MethodParameterUtils.getRequestDataType(parameter);
			Object paramObj = JSON.parseObject(obj.toString(), clazz);
			baseInput.setParams(paramObj);
		}
		return baseInput;
	}

}
